<?php
/*
 * 文章栏目管理
 */
class ArctypeAction extends CommonAction{
    
    /*
     * 列表
     */
    public function index(){
        if(!S('zixuntype'))$this->cache_type();
        $this->assign("zixuntype", S('zixuntype'));
        $this->display();
    }
    
    /*
     * 资讯增加
     */
    public function add(){
        $m = D('Arctype');
        if(IS_POST){            
            if(false === $m->create()){$this->error($m->getError());}            
            if(false === $m->add()){$this->error('添加失败');}
            $this->cache_type();
            $this->success('添加成功');exit();
        }        
        $list = $m->order('topid asc,id desc')->select();
        $this->assign('list',  Tool::tree($list));
        $m2 = M('channel');
        $channel = $m2->select();
        $this->assign('channel',$channel);
        $this->display();
    }
    
    /*
     * 资讯修改
     */
    public function edit($id){
        $m = D('Arctype');
        $list = $m->find($id);
        if(IS_POST){
            $data = $m->order('topid asc,id desc')->select();
            $uid = Tool::tree($data,$list['id']);
            foreach($uid as $k=>$v){
                $ids[] = $v['id'];
            }
            if(in_array(I('post.topid'),$ids)){$this->error("当前栏目不允许移动到它的子级栏目");}
            if(false === $m->create()){$this->error($m->getError());}  
            if(false === $m->save()){$this->error('修改失败');}
            $this->cache_type();
            $this->success('修改成功');exit();
        }        
        $this->assign('list',$list);
        $tree = $m->order('topid asc,id desc')->select();
        $this->assign('tree',  Tool::tree($tree));
        $m2 = M('channel');
        $channel = $m2->where(array('id'=>$list['channelid']))->find();
        $this->assign('channel',$channel);
        $this->display();
    }
    
    /*
     * 资讯栏目删除
     */
    public function del($id){
        $m = M('archive');
        $list = $m->where(array('typeid'=>$id))->find();        
        if($list){$this->error('本栏目下面有文章，不允许删除');}
        $m2 = M('arctype');
        $list2 = $m2->where(array('topid'=>$id))->find();
        if($list2){$this->error('本栏目下面有栏目，不允许删除');}
        if($m2->delete($id)){
            $this->cache_type();
            $this->success('删除成功');exit();}
        $this->error('删除失败');
    }
    
    /*
     * 缓存栏目
     */
    protected function cache_type(){
        $map['topid'] = 0;
        $other['order'] = 'sort desc,id asc';
        $digui = digui('arctype',$map,$other);
        S('zixuntype',$digui);
    }
}